package com.bora_bandeco;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class BoraBandecoProvider extends ContentProvider {
	public static final String PROVIDER_NAME = "com.bora_bandeco.bandecoprovider";
	
	public static final Uri CONTENT_URI_CONTATOS = Uri.parse("content://" + PROVIDER_NAME + "/contatos");
	public static final Uri CONTENT_URI_CONVITES = Uri.parse("content://" + PROVIDER_NAME + "/convites");
	
	private static final int CONTATOS = 1;
	private static final int CONTATO_ID = 2;
	private static final int CONVITES = 3;
	private static final int CONVITE_ID = 4;
	
	public static final String TABELA_CONTATOS = "contatos";
	public static final String TABELA_CONVITES = "convites";
	public static final String TABELA_R_CONVITES_CONTATOS = "r_convites_contatos";
	
	public static final String _ID = "_id";
	
	private static final UriMatcher uriMatcher;
	static {
	    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	    uriMatcher.addURI(PROVIDER_NAME, "contatos", CONTATOS);
	    uriMatcher.addURI(PROVIDER_NAME, "contatos/#", CONTATO_ID);      
	    uriMatcher.addURI(PROVIDER_NAME, "convites", CONVITES);
	    uriMatcher.addURI(PROVIDER_NAME, "convites/#", CONVITE_ID);      
	}
	
	protected static DbHelper dbHelper;
	
	// O sistema chama onCreate() quando inicializa o provider 
	@Override
	public boolean onCreate() {
		dbHelper = new DbHelper(getContext());
		
		// Se já houver cadastro faz-se o fetch de contatos
		SharedPreferences preferences = getContext().getSharedPreferences("com.bora_bandeco", Context.MODE_PRIVATE);
        int meuIdContato = preferences.getInt("_id", 0);
        
		if (meuIdContato != 0) {
			ContatosFetcher fetcher = new ContatosFetcher(getContext());
			fetcher.execute();
		}
		
		return true;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		Uri _uri = null;
		int uriType = uriMatcher.match(uri);
		SQLiteDatabase db = dbHelper.getWritableDatabase();

	    switch (uriType){ 
		    case CONTATOS:
		    	long _ID_CONTATO = db.insert(TABELA_CONTATOS, "", values);

		    	if (_ID_CONTATO > 0) {
		    		_uri = ContentUris.withAppendedId(CONTENT_URI_CONTATOS, _ID_CONTATO);
		    		getContext().getContentResolver().notifyChange(_uri, null);    
		    	}
		        break;
		    	
		    case CONVITES:
		        long _ID_CONVITE = db.insert(TABELA_CONVITES, "", values);
		        
		        if (_ID_CONVITE > 0) {
		            _uri = ContentUris.withAppendedId(CONTENT_URI_CONVITES, _ID_CONVITE);
		            getContext().getContentResolver().notifyChange(_uri, null);    
		        }
		        break;
	        
	    	default: throw new SQLException("Failed to insert row into " + uri);
	    }
	    return _uri;                
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Cursor returnValue = null;
		int uriType = uriMatcher.match(uri);
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		
	    switch (uriType){ 
		    case CONTATOS:
		    	returnValue = db.query(TABELA_CONTATOS, projection, null, null, null, null, null, null);
		    	break;
	    	
		    case CONTATO_ID:
		    	returnValue = db.query(TABELA_CONTATOS, projection, _ID + "=" + this.getArgValue(uri), null, null, null, null, "1");
		    	break;
		    	
		    case CONVITES:
		    	returnValue = db.query(TABELA_CONVITES, projection, null, null, null, null, null, null);
		    	break;
		    
		    case CONVITE_ID:
		    	returnValue = db.query(TABELA_CONVITES, projection, _ID + "=" + this.getArgValue(uri), null, null, null, null, "1");
		    	break;
		    	
		    default: throw new SQLException("Failed to query values from " + uri);
	    }
		
		return returnValue;
	}

	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		return 0;
	}

	private String getArgValue(Uri uri) {
		String argValue = uri.getLastPathSegment();
		
		return argValue;
	}
	
	
	class DbHelper extends SQLiteOpenHelper {
		static final String DATABASE = "bora_bandeco.db";
		static final int VERSION = 1;
		
		private static final String TABELA_CONTATOS = "contatos";
		private static final String TABELA_CONVITES = "convites";
		private static final String TABELA_R_CONVITES_CONTATOS = "r_convites_contatos";
		
		private static final String CREATE_TABLE_CONTATOS =
		    "CREATE TABLE IF NOT EXISTS " + TABELA_CONTATOS + 
		    " (_id INTEGER PRIMARY KEY, " + 
		    "  nome text, foto text, numero_telefone text);";
		
		private static final String CREATE_TABLE_CONVITES =
		    "CREATE TABLE IF NOT EXISTS " + TABELA_CONVITES + 
		    " (_id INTEGER PRIMARY KEY, " + 
		    "  horario INTEGER, restaurante text, anfitriao INTEGER, cardapio text);";
		
		private static final String CREATE_TABLE_R_CONVITES_CONTATOS =
			    "CREATE TABLE IF NOT EXISTS " + TABELA_R_CONVITES_CONTATOS + 
			    " (id_convite INTEGER, id_contato INTEGER, resposta INTEGER);";
		
		public DbHelper(Context context) {
			super(context, DATABASE, null, VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE_TABLE_CONTATOS);
			db.execSQL(CREATE_TABLE_CONVITES);
			db.execSQL(CREATE_TABLE_R_CONVITES_CONTATOS);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABELA_CONTATOS);
			db.execSQL("DROP TABLE IF EXISTS " + TABELA_CONVITES);
			db.execSQL("DROP TABLE IF EXISTS " + TABELA_R_CONVITES_CONTATOS);
			onCreate(db);
		}
	}
}
